package com.gxa.servlet.activity;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.pojo.Result;
import com.gxa.pojo.activity.Activity;
import com.gxa.pojo.activity.ActivityType;
import com.gxa.pojo.activity.Activitys;
import com.gxa.service.avticity.ActivityService;
import com.gxa.service.avticity.impl.ActivityServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet(urlPatterns = "/addActivity")
public class AddActivityServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        ActivityService activityService = new ActivityServiceImpl();

        BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(),"UTF-8"));
        StringBuilder json = new StringBuilder();
        String inputStr;
        while ((inputStr = streamReader.readLine()) != null) {
            json.append(inputStr);
        }
        String jsonString = json.toString();

        Activitys activitys = JSON.parseObject(jsonString, Activitys.class);
        int activityTypeId = activityService.findActivityTypeId(activitys.getType());
        Activity activity = new Activity(0,activitys.getAname(),activityTypeId,activitys.getStarttime(),activitys.getEndtime(),activitys.getNote(),activitys.isState(),null);
        boolean b = activityService.addActivity(activity);
        PrintWriter writer = response.getWriter();
        Map<String,Object> map = new HashMap<>();
        String s= null;
        if (b){
            map.put("result", Result.ok("success"));
            s= objectMapper.writeValueAsString(map);

        }else {
            map.put("result",Result.error());
            s= objectMapper.writeValueAsString(map);
        }
        writer.write(s);
        writer.flush();
        writer.close();
        streamReader.close();
    }
}
